package tsinghua.smxq.mc;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import tsinghua.smxq.foodprice.HttpConnection;
import tsinghua.smxq.ui.MCListViewListener;
import tsinghua.smxq.ui.MCMenuAdapter;
import tsinghua.smxq.ui.MCMenuView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

public class FoodPriceRequestActivity extends Activity {
	private List<String> proset = new ArrayList<String>();
	ArrayList<String> city_list = new ArrayList<String>();
	ArrayList<String> market_list = new ArrayList<String>();
	ArrayList<String> foodcategory_list = new ArrayList<String>();
	ArrayList<String> foodname_list = new ArrayList<String>();
	ArrayAdapter<String> pro_adapter, city_adapter, foodcategory_adapter,
			foodname_adapter;
	ArrayAdapter<Integer> day_adapter;
	Spinner pro_spinner, city_spinner, foodcategory_spinner, foodname_spinner;
	String city, food, time;
	private String cityID;
	private int pro_id;
	int foodID;
	URL url;
	ImageButton start_button;
	RadioGroup radiogroup;
	RadioButton radiobutton1, radiobutton2;
	Toast toast;
	String[] cityls, foodnamels, foodcategoryls;
	int selectedfoodcategory;
	private File f = new File("/data/data/tsinghua.smxq.mc/databases/data.db");
	Button menuBtn;
	LayoutInflater inflater;
	ImageButton mBtnChooseType = null;
	public MCMenuView menuView;
	private ListView menuList;
	private View RightView;
	private View[] children;
	private MCMenuAdapter menuAdapter;
	private MCListViewListener menuListener;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		inflater = inflater.from(this);

		setContentView(inflater.inflate(R.layout.menu_scroll_view, null));
		RightView = inflater.inflate(R.layout.foodpricerequest, null);
		menuView = (MCMenuView) findViewById(R.id.mScrollView);
		menuAdapter = new MCMenuAdapter(this);

		menuList = (ListView) findViewById(R.id.menuList);
		menuListener = new MCListViewListener(this);
		menuList.setAdapter(menuAdapter);
		menuList.setOnItemClickListener(menuListener);
		menuBtn = (Button) RightView.findViewById(R.id.profile_menuBtn);
		menuBtn.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				FoodPriceRequestActivity.this.menuView.clickMenuBtn();
			}

		});

		pro_spinner = (Spinner) RightView.findViewById(R.id.pros_Spinner);
		pro_adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, getProSet());
		pro_spinner.setAdapter(pro_adapter);
		pro_spinner.setOnItemSelectedListener(new SelectProvince());
		
		city_spinner = (Spinner) RightView.findViewById(R.id.cities_Spinner);
		pro_id = 0;
		city_spinner.setAdapter(getAdapter());
		city_spinner
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						city = city_spinner.getSelectedItem().toString();
						cityID = String.valueOf(arg2 + 1);
						// cityID = ""+String.valueOf(pro_id)+arg2;
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}
				});
		// 食物类别
		foodcategory_spinner = (Spinner) RightView
				.findViewById(R.id.foodcategory_Spinner);
		foodcategoryls = getResources().getStringArray(R.array.foodcategories);
		// 获取XML中定义的数组
		for (int i = 0; i < foodcategoryls.length; i++) {
			foodcategory_list.add(foodcategoryls[i]);
		}
		// 把数组导入到spinner中
		foodcategory_adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, foodcategory_list);
		// 设置下拉菜单的风格
		foodcategory_adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 绑定适配器
		foodcategory_spinner.setAdapter(foodcategory_adapter);
		foodcategory_spinner.setPrompt("食物类别");
		foodcategory_spinner
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						UpdateFoodName_Spinner(arg2);
						arg0.setVisibility(View.VISIBLE);
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
					}
				});
		
		
		
		// 食物名称
		foodname_spinner = (Spinner) RightView	.findViewById(R.id.foodname_Spinner);
		UpdateFoodName_Spinner(0);
		foodname_spinner
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						food = foodname_spinner.getSelectedItem().toString();
						foodID = arg2 + 1;
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}
				});

		// 获得开始按钮
		start_button = (ImageButton) RightView
				.findViewById(R.id.imgbutton_start);
		start_button.setOnClickListener(new OnClickListener() {// 添加按钮监听器
					public void onClick(View v) {
						DisplayToast("cityID : " + cityID + "\ncity :" + city
								+ "\nfoodID： : " + foodID + "\nfood : " + food,
								Toast.LENGTH_SHORT);
						// 连接服务器 ，更新cityfoodprice.xml文件
						try {
							url = new URL("http://" + Constants.serverIP
									+ ":8080/MobileCityServer/queryPrice.do?"
									+ "cityId=" + cityID + "&foodId=" + foodID);
							String result = HttpConnection.httpConnection(url)
									.trim();
							if (result.length() == 0) {
								DisplayToast("查询为空", Toast.LENGTH_LONG);
							} else if (result.compareToIgnoreCase("failure") == 0) {
								DisplayToast("查询失败", Toast.LENGTH_LONG);
							} else {
								DisplayToast("查询成功", Toast.LENGTH_LONG);
								showCityFoodPriceDialog(cityID, city, result,
										food, foodID);
							}
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				});

		mBtnChooseType = (ImageButton) RightView
				.findViewById(R.id.ib_chooseType);
		mBtnChooseType.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new AlertDialog.Builder(FoodPriceRequestActivity.this)
						.setTitle("菜价搜索功能")
						.setItems(new String[] { "菜价搜索", "菜价提交", "历史菜价" },
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub
										if (which == 0) {
											return;
										} else if (which == 1) {
											Intent intent = new Intent();
											intent.setClass(
													FoodPriceRequestActivity.this,
													FoodPriceSubmitActivity.class);
											FoodPriceRequestActivity.this
													.startActivity(intent);
										} else if (which == 2) {
											Intent intent = new Intent();
											intent.setClass(
													FoodPriceRequestActivity.this,
													HistoryChartActivity.class);
											FoodPriceRequestActivity.this
													.startActivity(intent);

										}

									}
								}).create().show();
			}

		});

		View leftView = new View(this);
		children = new View[] { leftView, RightView };
		leftView.setBackgroundColor(Color.TRANSPARENT);
		this.menuView.initViews(children, this.menuBtn, this.menuList);
		this.menuView.setMenuBtn(this.menuBtn);
		MCMenuAdapter.currPosition = 2;
	}

	// 显示菜价信息
	public void showCityFoodPriceDialog(final String cityId, final String city,
			String price, final String food, final int foodId) {
		new AlertDialog.Builder(this)
				/** 设置标题 **/
				.setTitle("查询结果")
				/** 设置icon **/
				.setIcon(android.R.drawable.btn_star)
				/** 设置内容 **/
				.setMessage(city + "最新" + food + "价格为：" + price)
				.setNegativeButton("查看价格波动",
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								Intent gotoIntent = new Intent(
										FoodPriceRequestActivity.this,
										FoodPriceLineChartActivity.class);
								gotoIntent.putExtra("cityId",
										Integer.parseInt(cityId));
								gotoIntent.putExtra("city", city);
								gotoIntent.putExtra("food", food);
								gotoIntent.putExtra("foodId", foodId);
								FoodPriceRequestActivity.this
										.startActivity(gotoIntent);

							}
						})
				.setPositiveButton("关闭", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();

					}
				}).show();

	}

	/**
	 * 返回 省份集合
	 */
	public List<String> getProSet() {
		SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(f, null);
		Cursor cursor = db1.query("provinces", null, null, null, null, null,
				null);
		while (cursor.moveToNext()) {
			String pro = cursor.getString(cursor.getColumnIndexOrThrow("name"));
			proset.add(pro);
		}
		cursor.close();
		db1.close();
		return proset;
	}

	class SelectProvince implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			// TODO Auto-generated method stub
			pro_id = position;
			city_spinner.setAdapter(getAdapter());

		}

		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}
	}

	public ArrayAdapter<String> getAdapter() {
		ArrayAdapter<String> adapter1 = new ArrayAdapter(this,
				android.R.layout.simple_spinner_item, getCitSet(pro_id));
		return adapter1;
	}

	/**
	 * 返回 城市集合
	 */
	public List<String> getCitSet(int pro_id) {
		city_list.clear();
		SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(f, null);
		Cursor cursor = db1.query("citys", null, "province_id=" + pro_id, null,
				null, null, null);
		while (cursor.moveToNext()) {
			String pro = cursor.getString(cursor.getColumnIndexOrThrow("name"));
			city_list.add(pro);
		}
		cursor.close();
		db1.close();
		return city_list;
	}

	public void DisplayToast(String str, int time) {
		toast = Toast.makeText(this, str, time);
		// 设置toast显示的位置
		toast.setGravity(Gravity.TOP, 0, 320);
		// 显示该Toast
		toast.show();
	}

	/*
	 * public void UpdateMarket_Spinner(String ct) {
	 * if(ct.compareToIgnoreCase("beijing")== 0) {
	 * marketls=getResources().getStringArray(R.array.beijing); //获取XML中定义的数组
	 * market_list.clear(); for(int i=0;i<marketls.length;i++) {
	 * market_list.add(marketls[i]); } } else if(ct.compareToIgnoreCase("上海")==
	 * 0) { marketls=getResources().getStringArray(R.array.shanghai);
	 * //获取XML中定义的数组 market_list.clear(); for(int i=0;i<marketls.length;i++) {
	 * market_list.add(marketls[i]); } } else
	 * if(ct.compareToIgnoreCase("shenzhen")== 0) {
	 * marketls=getResources().getStringArray(R.array.shenzhen); //获取XML中定义的数组
	 * market_list.clear(); for(int i=0;i<marketls.length;i++) {
	 * market_list.add(marketls[i]); } }
	 * 
	 * //把数组导入到spinner中 market_adapter=new
	 * ArrayAdapter<String>(this,android.R.layout
	 * .simple_spinner_item,market_list); //设置下拉菜单的风格
	 * market_adapter.setDropDownViewResource
	 * (android.R.layout.simple_spinner_dropdown_item); //绑定适配器
	 * market_spinner.setAdapter(market_adapter);
	 * market_spinner.setPrompt("市场名称");
	 * 
	 * }
	 */
	public void UpdateFoodName_Spinner(int selectedcategory) {
		foodname_list.clear();
		switch (selectedcategory) {
		case 0:
			foodnamels = getResources().getStringArray(R.array.Meat);
			// 获取XML中定义的数组
			for (int i = 0; i < foodnamels.length; i++) {
				foodname_list.add(foodnamels[i]);
			}
			break;
		case 1:
			foodnamels = getResources().getStringArray(R.array.Vegetable);
			// 获取XML中定义的数组
			for (int i = 0; i < foodnamels.length; i++) {
				foodname_list.add(foodnamels[i]);
			}
			break;
		case 2:
			foodnamels = getResources().getStringArray(R.array.CookedFood);
			// 获取XML中定义的数组
			for (int i = 0; i < foodnamels.length; i++) {
				foodname_list.add(foodnamels[i]);
			}
			break;
		}
		// 把数组导入到spinner中
		foodname_adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, foodname_list);
		// 设置下拉菜单的风格
		foodname_adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 绑定适配器
		foodname_spinner.setAdapter(foodname_adapter);
		foodname_spinner.setPrompt("食物名称");
	}

}
